/**
 * Created by chenxq on 2017/12/28.
 */
import React,{PureComponent,Component} from 'react';
import moment from 'moment';
import { connect } from 'dva';
import { Form ,Input  ,Select  ,Modal,Radio,Row,Col,message} from 'antd';
import {Incomes,Costs,payTypes,signStatus} from '../../routes/defaultData';
import {reg} from '../../utils/CheckList';
import styles from '../../routes/TableList.less';
const FormItem=Form.Item;
const { Option } = Select;
const RadioGroup =Radio.Group;
@connect(state=>({
  account:state.account,
  userManage:state.usermanagement
}))
@Form.create()
export default class extends Component{
  static defaultProps={
    info:{},
    type:'income',
    onSubmit:null,
    onCancel:null,
    isvisible:false
  }

  submit=()=>{
    let {info,type} = this.props;
    let _this=this;
    this.props.form.validateFieldsAndScroll((err,values)=> {
      if (!err) {
        let params={
          id:info.id,
          loanId:info.loanId,
          flag:type,
          ...values
        }
        params.amount=parseInt(params.amount * 100,10);
        let fetchType=info.id?'account/fetchEdit':'account/fetchAdd';
        _this.props.dispatch({
          type:fetchType,
          payload:params
        }).then(jsonData=>{
          if(jsonData.result){
            message.success('提交成功',0.8,()=>{
              _this.props.onCancel && _this.props.onCancel();
              _this.updateAccountList(info.loanId);
            })
          }else{
            message.error(jsonData.msg || '提交失败');
          }
        })
      }
    })
  }

  //更新 列表
  updateAccountList=(loanId)=>{
    let {pagination} = this.props.account;
    if(pagination.current){
      if(!this.props.info.id){
        pagination.current=1;
      }
      this.props.dispatch({
        type:'account/fetchList',
        paylaod:{
          ...pagination
        }
      })
    }
    this.props.dispatch({
      type:'account/fetchListByLoanId',
      payload:loanId
    })

  }

  cancel=()=>{
    this.props.onCancel && this.props.onCancel()
  }

  getFormCell=()=>{
    let {info,type,userManage}= this.props;
    let typeArr= type=='income'?Incomes:Costs;
    let userList=userManage.allList || [];
    let handleValidator= function(rule,val,callback){
      if(!val){
        callback();
        return;
      }
      if(userList.findIndex(item=>item.id==val)>=0){
        callback();
      }else{
        callback('用户不存在')
      }
    }
    return [{
      label:'类别',
      key:'type',
      component: <Select placeholder="请选择">
        {typeArr.map(item=>(<Option key={item.key} value={item.key}>{item.name}</Option>))}
      </Select>,
      field:{rules:[{required:true,message:'请选择类别'}]},
    },
      {
        label:type=='income'?'收入人':'支出人',
        key:'person',
        component: <Select mode="combobox"
                           placeholder="请选择"
                           optionFilterProp="children"
                           optionLabelProp="children"
        >
          {userList.map((item,index)=>(<Option key={item.id} value={item.id}>{item.userName}</Option>))}
        </Select>,
        field:{
          initialValue:info.person,
          rules:[{required:true,message:`请选择`+(type=='income'?'收入人':'支出人')},{
            validator: handleValidator
          }]
        }
      },
      {
        label:'金额',
        key:'amount',
        component: <Input placeholder="请输入金额" />,
        field:{
          initialValue: (!!info.amount ? (info.amount/100).toFixed(2) : ''),
          rules:[{
            required:true,message:'请输入金额'
          },{pattern:reg.money,message:'输入格式不正确'}]
        }
      },
      {
        label:'支付方式',
        key:'payWay',
        component: <Select placeholder="请选择">
          {payTypes.map(item=>(<Option key={item.key} value={item.key}>{item.name}</Option>))}
        </Select>,
      },
      {
        label:'状态',
        key:'state',
        component: <RadioGroup>
          <Radio value={1}>已支付</Radio>
          <Radio value={0}>未支付</Radio>
        </RadioGroup>,
      },
      {
        label:`${type=='income'?'收入':'支出'}日期`,
        key:'date',
        component: <Input placeholder={`请输入${type=='income'?'收入':'支出'}日期`} />,
      },{
        label:'备注',
        key:'remark',
        span:24,
        formItemLayout : {
          labelCol: {
            xs: { span: 24 },
            sm: { span: 4 },
          },
          wrapperCol: {
            xs: { span: 24 },
            sm: { span: 16 },
          },
        },
        component: <Input.TextArea  placeholder="请输入备注"  />
      }
    ]
  }


  render(){
    let {getFieldDecorator} = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    let {info,type} = this.props;
    return (<Modal title={(info.id?'编辑':'新增')+(type=='income'?'收入':'支出')}
                   onOk={this.submit}
                   onCancel={this.cancel}
                   width={750}
                   visible={this.props.isvisible}
    >
      <Form className={styles.modal}>
        <Row gutter={24}>
          {this.getFormCell().map((item)=>{
            return <Col span={item.span || 12} key={item.key}>
              <FormItem label={item.label} {...(item.formItemLayout || formItemLayout)}>
                {getFieldDecorator(item.key,{
                  initialValue:info[item.key],
                  ...item.field
                })(
                  item.component
                )}
              </FormItem>
            </Col>
          })}
        </Row>
      </Form>

    </Modal>)
  }
}
